package com.smt.modules.bus.service.impl;

import com.smt.common.enums.Code;
import com.smt.common.utils.EnumToKeyUtil;
import com.smt.common.utils.R;
import com.smt.modules.bus.entity.*;
import com.smt.modules.bus.service.*;
import com.smt.modules.bus.vo.request.LoadFileReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.smt.common.utils.PageUtils;
import com.smt.common.utils.Query;

import com.smt.modules.bus.dao.DocPageDao;


@Service("docPageService")
public class DocPageServiceImpl extends ServiceImpl<DocPageDao, DocPageEntity> implements DocPageService {

    @Autowired
    private ProjectTaskService projectTaskService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    @Qualifier("documentManageService")
    private DocumentManageService documentManageService;

    @Autowired
    private AttachmentService attachmentService;

    @Autowired
    private SubtaskService subtaskService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<DocPageEntity> page = this.selectPage(
                new Query<DocPageEntity>(params).getPage(),
                new EntityWrapper<DocPageEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R docBackPage(List<LoadFileReq> loadFileReqList, MemberUserEntity memberUserEntity) {
        for(LoadFileReq loadFileReq : loadFileReqList) {
            Long userId = memberUserEntity.getUserId();
            //该用户的打包权限
            if (loadFileReq != null) {
                //获取项目id查找项目创建人
                Long projectId = loadFileReq.getProjectId();
                ProjectEntity projectEntity = projectService.selectById(projectId);
                if (!Objects.isNull(projectEntity)) {
                    boolean pression = isPression(projectEntity,userId);
                    if(pression){
                        return documentManageService.docBackPage(loadFileReq, memberUserEntity);
                    }else{
                        return R.error(EnumToKeyUtil.toInt(Code.MISSING_PERMISSION), "您没有权限打包文件");
                    }
                } else {
                    return R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR), "项目不能为空！");
                }
            }
        }
        return R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR), "参数错误！");
    }

    @Override
    public R docBackPageList(LoadFileReq loadFileReq, MemberUserEntity memberUserEntity) {
        Long projectId = loadFileReq.getProjectId();
        List<DocPageEntity> docPageEntities = selectList(new EntityWrapper<DocPageEntity>()
                .eq("project_id", projectId)
                .eq("valid", 0));
        List<Map<String,Object>> docList = new ArrayList<>();
        docPageEntities.stream().forEach(d -> {
            Map<String,Object> docMap = new HashMap<>();
            String packName = d.getPackName();
            String id = d.getBatch();
            Date createTime = d.getCreateTime();
            docMap.put("id",id);
            docMap.put("name",packName);
            docMap.put("createTime",createTime);
            docMap.put("statusType",1);
            boolean flag = true;
            for(Map<String,Object> m : docList){
                String batchId = (String)m.get("id");
                if(id.equals(batchId)){
                    flag = false;
                    break;
                }
            }
            if(flag){
                docList.add(docMap);
            }
        });
        return R.ok("返回打包文件列表成功").put("docList",docList);
    }

    @Override
    public R docBackPageInfo(Long id, MemberUserEntity memberUserEntity) {
        List<DocPageEntity> docPageEntities = null;
        if(!Objects.isNull(id)) {
            docPageEntities = selectList(new EntityWrapper<DocPageEntity>()
            .eq("batch",id)
            .eq("valid",0));
            docPageEntities.stream().forEach(d -> {
                Long taskId = d.getTaskId();
                    //动态添加文件路径
                    AttachmentEntity attachmentEntity = attachmentService.selectById(d.getAttachmentId());
                    String url = attachmentEntity.getUrl();
                    d.setFileUrl(url);
                    //添加文件后缀名
                    String suffFileName = new String(url);
                    String substring = suffFileName.substring(suffFileName.lastIndexOf("."), suffFileName.length());
                    //添加任务名
                    Long taskId1 = d.getTaskId();
                    Long subTaskId = d.getSubTaskId();
                    if(Objects.isNull(taskId1)){
                        SubtaskEntity subtaskEntity = subtaskService.selectById(subTaskId);
                        String subTaskName = subtaskEntity.getSubtaskName();
                        d.setTaskName(subTaskName+substring);
                        d.setType(0);
                    } else if (Objects.isNull(subTaskId)) {
                        ProjectTaskEntity projectTaskEntity = projectTaskService.selectById(taskId1);
                        String taskName = projectTaskEntity.getTaskName();
                        d.setTaskName(taskName+substring);
                        d.setType(1);
                    }
            });
        }
        return R.ok().put("fileList",docPageEntities);
    }

    @Override
    public R deleteDocBackPage(Long id,Long projectId, Long userId) {
        ProjectEntity projectEntity = projectService.selectById(projectId);
        if(!Objects.isNull(projectEntity)){
            boolean pression = isPression(projectEntity,userId);
            if(pression){
                DocPageEntity docPageEntity = new DocPageEntity();
                docPageEntity.setValid(1);
                boolean batch = update(docPageEntity, new EntityWrapper<DocPageEntity>()
                        .eq("batch", id));
                return batch?R.ok("删除成功！"):R.error(EnumToKeyUtil.toInt(Code.DELETE_DATA_ERROR),"删除数据失败！");
            }else{
                return R.error(EnumToKeyUtil.toInt(Code.MISSING_PERMISSION), "您没有权限删除此打包文件");
            }
        }else{
            return R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR), "项目不能为空！");
        }
    }

    /**
     * 检验权限
     *
     * @param projectId
     * @param userId
     * @return
     */
    @Override
    public R docBackPermission(Long projectId, Long userId) {
        ProjectEntity projectEntity = projectService.selectById(projectId);
        boolean pression = isPression(projectEntity, userId);
        return pression?R.ok("有权限"):R.error("无权限");
    }

    /**
     * 判断当前操作者是否有打包权限
     *
     * @param projectEntity
     * @param userId
     * @return
     */
    private boolean isPression(ProjectEntity projectEntity,Long userId){
        Long createdId = projectEntity.getCreatedId();
        Long projectId = projectEntity.getId();
        ProjectTaskEntity projectTaskStage = projectTaskService.selectOne(new EntityWrapper<ProjectTaskEntity>()
                .eq("project_id", projectId)
                .eq("status", 400)
                .eq("stage_id", 6));
        Long stageMemberId = projectTaskStage.getStageMemberId();
        if (!Objects.isNull(stageMemberId) && (stageMemberId.equals(userId) || createdId.equals(userId))) {
            return true;
        } else {
            return false;
        }
    }
}
